﻿using ContactSMS.Client.Response;
using ContactSMS.Client.Models;
using Newtonsoft.Json;
using System.Text;

namespace ContactSMS.Client.Service
{
    public class LoginService : BaseService
    {
        HttpClient httpClient;

        public LoginService()
        {
            this.httpClient = new HttpClient();
        }

        public async Task<QResponse<TokenData>> LoginAsync(string userName, string passWord)
        {
            string url = baseUrl + "/api/Login/Login";

            var requestData = new
            {
                userName = userName,
                passWord = passWord
            };

            var jsonContent = new StringContent(JsonConvert.SerializeObject(requestData), Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync(url, jsonContent);

            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                var loginResponse = JsonConvert.DeserializeObject<QResponse<TokenData>>(responseContent);
                return loginResponse;
            }
            else
            {
                return null;
            }
        }

        public async Task<QResponse<RegisterModel>> RegisterAsync(RegisterModel registerModel)
        {
            string url = baseUrl + "/api/Login/Register";

            var jsonContent = new StringContent(JsonConvert.SerializeObject(registerModel), Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync(url, jsonContent);

            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                var registerResponse = JsonConvert.DeserializeObject<QResponse<RegisterModel>>(responseContent);
                return registerResponse;
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                await Console.Out.WriteLineAsync($"Request failed with status code {response.StatusCode}: {errorContent}");
                return null;
            }
        }
    }
}
